package com.example.playlet.service.sensitive.impl;

import java.util.Arrays;
import java.util.Comparator;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.playlet.entity.sensitive.SensitiveWords;
import com.example.playlet.mapper.sensitive.SensitiveWordsMapper;
import com.example.playlet.service.sensitive.ISensitiveWordsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.Objects; // 添加这一行


@Service("sensitiveWordsService")
public class SensitiveWordsServiceImpl implements ISensitiveWordsService {
    private Logger logger = LoggerFactory.getLogger(SensitiveWordsServiceImpl.class);
    @Autowired
    private SensitiveWordsMapper sensitiveWordsMapper;
    private static volatile List<String> sensitiveWordList = new CopyOnWriteArrayList<>();

    @Override
    public List<SensitiveWords> selectResultQuery() {
        return sensitiveWordsMapper.selectResultQuery();
    }

    @PostConstruct
    public void loadSensitiveWords() {
        List<SensitiveWords> words = sensitiveWordsMapper.selectResultQuery();
        sensitiveWordList = words.stream()
                .map(SensitiveWords::getWords)
                .filter(Objects::nonNull)
                .flatMap(s -> Arrays.stream(s.split("\\|"))) // ✅ 改为 s
                .distinct()
                .sorted(Comparator.comparingInt(String::length).reversed())
                .collect(Collectors.toList());
    }

    public static List<String> getSensitiveWordList() {
        return sensitiveWordList;
    }

    @Override
    public String filterText(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        List<String> sortedWords = SensitiveWordsServiceImpl.getSensitiveWordList();

        for (String word : sortedWords) {
            System.out.println(text.contains(word));
            if (text.contains(word)) {
                text = text.replace(word, "***");
            }
        }
        return text;
    }
}
